<template>
  <div class="view-fill">
    <div
      class="app-container-flex"
      v-if="
        !dataEntryDetailsInfo.visible &&
        !storeDetailInfo.visible &&
        !exportDetailInfo.visible
      "
    >
      <NewFullScreen
        v-model="showDialog"
        @returnBack="returnBack"
        title="损益明细"
        :btnList="fullInfo.btnList"
      >
        <template v-slot:full-button>
          <el-button
            @click="showStoreOrder()"
            v-if="
              infoList.data.status === 3 &&
              infoList.data.inventoryStoreOrderId &&
              infoList.data.inventoryStoreOrderId !== -2
            "
            >盘点入库单</el-button
          >
          <el-button
            @click="showExportOrder()"
            v-if="
              infoList.data.status === 3 &&
              infoList.data.inventoryExportOrderId &&
              infoList.data.inventoryExportOrderId !== -2
            "
            >盘点出库单</el-button
          >
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation :info="infoList" />
          </div>
        </div>
        <div class="model-panel" v-if="infoList.data.useSub === 1">
          <div class="model-panel-title">
            <p>{{ $t('子盘点单') }}</p>
          </div>
          <div class="model-panel-body">
            <PageTable
              :pager="false"
              v-model:data="tableItemInfo.data"
              :field-list="tableItemInfo.fieldList"
              :handle="tableItemInfo.handle"
              :check-box="false"
              :highlight-row="false"
            />
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <NewPageFilter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.list"
            >
              <template v-slot:filter-selectMode>
                <el-select
                  @change="getList"
                  clearable
                  v-model="filterInfo.query.queryParams.selectMode"
                >
                  <el-option
                    :value="item.code"
                    v-for="(item, index) in filterInfo.data.selectModeOption"
                    :key="index"
                    :label="item.name"
                  />
                </el-select>
              </template>
            </NewPageFilter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :pager="false"
                :row-class-name="rowClassName"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="true"
                v-model:query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
              </PageTable>
            </div>
          </div>
        </div>
      </NewFullScreen>
      <individual-details
        v-if="individualDetailsInfo.visible"
        v-model:show-dialog="individualDetailsInfo.visible"
        :api="individualDetailsInfo.api"
        :tableKey="individualDetailsInfo.tableKey"
        v-model:query="individualDetailsInfo.query"
        :info="individualDetailsInfo.productInfo"
      ></individual-details>
    </div>
    <DataEntryDetails
      v-if="dataEntryDetailsInfo.visible"
      v-model:visible="dataEntryDetailsInfo.visible"
      :tableRow="dataEntryDetailsInfo.tableRow"
      :title="dataEntryDetailsInfo.title"
      @callback="getCustomize"
    />
    <InventoryAndExportDetail
      v-if="exportDetailInfo.visible"
      v-model:visible="exportDetailInfo.visible"
      :table-row="exportDetailInfo.data"
      @returnBack="getList"
    />
    <InventoryAndStorageDetail
      v-if="storeDetailInfo.visible"
      v-model:visible="storeDetailInfo.visible"
      :table-row="storeDetailInfo.data"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="inventory-profit-loss">
import {
  getInventoryOrderPrint,
  getInventoryDetailsCustomizeListAll,
  getInventoryOrderById,
  inventoriesExcel,
  inventoryDetailsDiffAll,
  inventoryOrderDetailExtAll,
  subInventoryOrderAll,
} from '@/api/stock'
import IndividualDetails from './IndividualDetails'
import InventoryAndExportDetail from '@/views/stock/inventoryAndExport/detail'
import InventoryAndStorageDetail from '@/views/stock/inventoryAndStorage/detail'
import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
const DataEntryDetails = defineAsyncComponent(() =>
  import('./dataEntryDetails')
)
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  tableRow: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const storeDetailInfo = ref({
  visible: false,
  data: {},
})
const exportDetailInfo = ref({
  visible: false,
  data: {},
})
const fullInfo = ref({
  btnList: [
    { value: 'button', type: 'slot' },
    {
      label: '打印',
      event: print,
      show: proxy.$permission('inventories:print'),
    },
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('inventories:exportExcel'),
    },
  ],
})
//主表相关
const infoList = ref({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'text' },
    { label: '仓库', value: 'depotName', type: 'text' },
    { label: '盘点人', value: 'inventoryUserName', type: 'text' },
    { label: '盘点时间', value: 'inventoryTime', type: 'text' },
    { label: '差异处理人', value: 'diffProcessUserName', type: 'text' },
    { label: '差异处理时间', value: 'diffProcessTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '最后更新人', value: 'updateUserName', type: 'text' },
    { label: '最后更新时间', value: 'updateTime', type: 'text' },
    { label: '是否子盘点单', value: 'useSubValue', type: 'text' },
    { label: '是否零星盘点单', value: 'sporadicValue', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'text',
    },
    { label: '备注', value: 'remark', type: 'popover' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    queryParams: {
      selectMode: '',
    },
  },
  data: {
    selectModeOption: proxy.$store.state.permission.dict['selectMode'] || [],
  },
  list: [
    {
      label: '筛选条件',
      value: 'selectMode',
      type: 'slot',
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  summaryFieldList: [
    { value: 'stockQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'diffQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'diffSumAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: singleProductDetails,
        show: true,
      },
    ],
  },
})
const tableItemInfo = ref({
  data: [],
  selections: [],
  fieldList: [
    { label: '房间号', value: 'roomNo' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '盘点人', value: 'inventoryUserName' },
    { label: '盘点时间', value: 'inventoryTime' },
    { label: '状态', value: 'statusValue' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '查看',
        event: getItemDetails,
        show: true,
        ifRender: function (row) {
          return row.status === 3
        },
      },
    ],
  },
})
const dataEntryDetailsInfo = ref({
  visible: false,
  title: '',
  tableRow: {},
})
const filterItemInfo = ref({
  query: {
    orderId: props.tableRow.id,
    sort: 'create_time desc',
  },
})
const individualDetailsInfo = ref({
  query: {
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
  },
  selectObj: {},
  visible: false,
  productInfo: {},
  api: getInventoryDetailsCustomizeListAll,
  tableKey:
    'stockInventoryDataEntryIndividualDetails-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})

function returnBack() {
  proxy.$emit('returnBack')
}
function getInfo() {
  getInventoryOrderById(props.tableRow.id).then((res) => {
    if (res && res.success) {
      infoList.value.data = res.data
      if (res.data.useSub === 1) {
        getItemList()
      }
      tableInfo.value.fieldList.find(i => {
        if(i.value == 'frozenQty') {
          console.log(res)
          i.hidden = res.data?.depotAllowFrozenInventory != 1
        }
      })
    }
  })
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 子盘点单
function getItemList() {
  subInventoryOrderAll(filterItemInfo.value.query).then((res) => {
    if (res && res.success) {
      tableItemInfo.value.data = res.data
    }
  })
}
// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function singleProductDetails(row) {
  individualDetailsInfo.value.productInfo = JSON.parse(JSON.stringify(row))
  individualDetailsInfo.value.query.orderId.value = props.tableRow.id
  if (Object.values(individualDetailsInfo.value.selectObj).length) {
    for (let key in individualDetailsInfo.value.selectObj) {
      individualDetailsInfo.value.selectObj[key].value = row[key]
    }
  } else {
    selectObj['depotStockId'] = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.depotStockId,
    }
  }
  individualDetailsInfo.value.query = {
    ...individualDetailsInfo.value.query,
    ...individualDetailsInfo.value.selectObj,
  }
  individualDetailsInfo.value.visible = true
}
function getItemDetails(row) {
  dataEntryDetailsInfo.value = {
    tableRow: row,
    title: '子盘点单详情',
    visible: true,
  }
}
function rowClassName({ row = undefined }) {
  let className = 'row' + row.id
  if (row.depotStockId === -2) {
    return 'warning-row'
  }
  return ''
}
// //跳转到盘点入库单
// function showStoreOrder() {
//   let params = {
//     id: infoList.value.data.inventoryStoreOrderId,
//   }
//   proxy.$router.push({
//     name: 'inventoryAndStorage',
//     params,
//   })
// }
// //跳转到盘点出库单
// function showExportOrder() {
//   let params = {
//     id: infoList.value.data.inventoryExportOrderId,
//   }
//   proxy.$router.push({
//     name: 'inventoryAndExport',
//     params,
//   })
// }
function showExportOrder() {
  // inventoryExportOrderId
  exportDetailInfo.value.visible = true
  exportDetailInfo.value.data = {
    id: infoList.value.data.inventoryExportOrderId,
  }
}
function showStoreOrder() {
  // inventoryStoreOrderId
  storeDetailInfo.value.visible = true
  storeDetailInfo.value.data = { id: infoList.value.data.inventoryStoreOrderId }
}
//打印
function print() {
  fatchTemplateByCode({
    resourceCode: 'inventories:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  })
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'stockInventoryDataEntry-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
    orderIds: [props.tableRow.id],
    queryParams: filterInfo.value.query.queryParams,
  }
  getInventoryOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('inventories:price')
      )
    }
  })
}
function exportExcel() {
  inventoriesExcel(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function getDifference() {
  inventoryDetailsDiffAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'stockInventoryDataEntry-com.slip.spd.entity.vo.stock.InventoryOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let obj = {}
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
        }
      }
      individualDetailsInfo.value.selectObj = obj
      tableInfo.value.api = getInventoryDetailsCustomizeListAll
      getInfo()
      getList()
    }
  })
}

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    show: false,
    hidden: true,
  },
  diffSumAmount: {
    label: '盘点差异金额',
    value: 'diffSumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '盘点金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('inventories:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('inventories:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
</script>

<style scoped lang="scss">
:deep(.el-table) .warning-row {
  background: #f5e4e4;
}
</style>
